package com.tms.warehouse.mappings;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.tms.warehouse.Warehouse;
import com.tms.warehouse.entity.Color;
import com.tms.warehouse.entity.Profile;
import com.tms.warehouse.entity.ProfileType;
import com.tms.warehouse.entity.Shelf;

public class ProfileMapper extends AbstractMapper<Profile> {

	private static final String ENTITY_NAME = "Profile";
	private static final String PROPERTY_COUNT = "count";
	private static final String PROPERTY_LENGTH = "lenth";
	private static final String PROPERTY_NOTICE = "notice";
	private static final String PROPERTY_TYPE = "profileType";
	private static final String PROPERTY_COLOR = "color";
	private static final String PROPERTY_SHELF = "shelf";

	@Override
	public String getType() {

		return ENTITY_NAME;
	}

	@Override
	public Profile wrap(Entity entity) {

		long count = (Long) entity.getProperty(PROPERTY_COUNT);
		long length = (Long) entity.getProperty(PROPERTY_LENGTH);
		String notice = (String) entity.getProperty(PROPERTY_NOTICE);
		Key typeKey = (Key) entity.getProperty(PROPERTY_TYPE);
		ProfileType type = typeKey == null ? null : Warehouse
				.findProfileTypeById(String.valueOf(typeKey.getId()));
		Key colorKey = (Key) entity.getProperty(PROPERTY_COLOR);
		Color color = typeKey == null ? null : Warehouse.findColorById(String
				.valueOf(colorKey.getId()));
		Key shelfKey = (Key) entity.getProperty(PROPERTY_SHELF);
		Shelf shelf = typeKey == null ? null : Warehouse.findShelfById(String
				.valueOf(shelfKey.getId()));
		long id = entity.getKey().getId();
		return new Profile(id, (int) length, (int) count, notice, type, color,
				shelf);
	}

	@Override
	public Entity unwrap(Profile entity) {

		Entity profile;
		if(entity.getId() > 0) {
			profile = new Entity(createKey(entity.getId()));
		} else {
			profile = new Entity(ENTITY_NAME);			
		}
		profile.setProperty(PROPERTY_COUNT, entity.getCount());
		profile.setProperty(PROPERTY_LENGTH, entity.getLength());
		profile.setProperty(PROPERTY_NOTICE, entity.getNotice());
		profile.setProperty(PROPERTY_TYPE,
				mapRelation(entity.getProfileType(), new ProfileTypeMapper()));
		profile.setProperty(PROPERTY_SHELF,
				mapRelation(entity.getShelf(), new ShelfMapper()));
		profile.setProperty(PROPERTY_COLOR,
				mapRelation(entity.getColor(), new AbstractMapper<Color>(){}));
		return profile;
	}
}
